package com.sample.dao.impl;

import java.util.List;

import org.hibernate.criterion.Restrictions;

import com.sample.Utils;
import com.sample.dao.ProjectDAO;
import com.sample.model.Project;
import com.sample.model.UserProject;
import com.trg.search.ISearch;
import com.trg.search.SearchResult;

public class ProjectDAOImpl extends BaseGenericDAO<Project, Long> implements
		ProjectDAO {
	@Override
	public void create(Project project) {
		super.create(project);

		if (project.getUsers() != null) {
			for (UserProject userProject : project.getUsers()) {
				if (userProject.getBillRate() != null
						&& userProject.getBillRate().isNaN()) {
					userProject.setBillRate(null);
				}
				userProject.setProject(project);

				userProject.setId(null);
				getSession().save(userProject);
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Project project) {
		super.update(project);
		
		List<UserProject> prev = getSession().createCriteria(UserProject.class)
				.add(Restrictions.eq("project.id", project.getId())).list();

		if (project.getUsers() == null) {
			project.setUsers(prev);
		} else {
outerLoop:	for (UserProject userProject : project.getUsers()) {
				if (userProject.getBillRate() != null
						&& userProject.getBillRate().isNaN()) {
					userProject.setBillRate(null);
				}
				userProject.setProject(project);

				for (int i = 0; i < prev.size(); i++) {
					UserProject prevUP = prev.get(i);
					if (prevUP.getUser().getId().equals( userProject.getUser().getId() ) ) {
						prevUP.setBillRate(userProject.getBillRate());
						prevUP.setStartDate(userProject.getStartDate());
						prevUP.setEndDate(userProject.getEndDate());
						prev.remove(i);
						//found
						continue outerLoop;
					}
				}

				//else, not found
				userProject.setId(null);
				getSession().save(userProject);
			}

			for (int i = 0; i < prev.size(); i++) {
				getSession().delete(prev.get(i));
			}
		}
	}

	@Override
	public List<Project> search(ISearch search) {
		return super.search(Utils.replaceSortProperty(search, "fullName",
				"name"));
	}

	@Override
	public SearchResult<Project> searchAndCount(ISearch search) {
		return super.searchAndCount(Utils.replaceSortProperty(search, "fullName", "name"));
	}
}